package com.gtqing.mall.controller;

import com.gtqing.mall.consts.MallConst;
import com.gtqing.mall.enums.ResponseEnum;
import com.gtqing.mall.form.UserLoginForm;
import com.gtqing.mall.form.UserRegisterForm;
import com.gtqing.mall.pojo.User;
import com.gtqing.mall.service.IUserService;
import com.gtqing.mall.vo.ResponseVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;

/**
 * @author gthang
 * @create 2022-04-09-9:51
 */
@RestController
@Slf4j
public class UserController {

    @Autowired
    private IUserService userService;

    @PostMapping("/user/register")
    public ResponseVo register(@Valid @RequestBody UserRegisterForm userRegisterForm){

        User user = new User();
        BeanUtils.copyProperties(userRegisterForm,user);

        return userService.register(user);
    }

    @PostMapping("/user/login")
    public ResponseVo<User> login(@Valid @RequestBody UserLoginForm userLoginForm,
                                  HttpSession session){
        ResponseVo<User> userResponseVo = userService.login(userLoginForm.getUsername(), userLoginForm.getPassword());

        //设置Session
        session.setAttribute(MallConst.CURRENT_USER,userResponseVo.getData());
        log.info("login sessionId={}",session.getId());
        return userResponseVo;
    }

    //session保存在内存里，容易数据流失  redis
    @GetMapping("/user")
    public ResponseVo<User> userInfo(HttpSession session){
        log.info("/user sessionId = {}",session.getId());
        User user = (User) session.getAttribute(MallConst.CURRENT_USER);
        if (user == null){

            return ResponseVo.error(ResponseEnum.NEED_LOGIN);
        }

        return ResponseVo.success(user);
    }

    //TODO 判断登录状态，拦截器
    @PostMapping("/user/logout")
    public ResponseVo logout(HttpSession session){
        log.info("/user/logout sessionId= {}", session.getId());

        session.removeAttribute(MallConst.CURRENT_USER);
        return ResponseVo.success();
    }

}
